package com.wang.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//处理默认的get提价 请求转发
		req.getRequestDispatcher("/jsp/login/register.jsp").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//创建一个磁盘文件项上传工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建一个servlet文件上传对象
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		
//		servletFileUpload.setFileSizeMax(1024);
		servletFileUpload.setSizeMax(1024*100);
		try {
			//通过文件上传对象解析请求得到一个list集合
			List<FileItem> parseRequest = servletFileUpload.parseRequest(req);
			for (FileItem fileItem : parseRequest) {
				if(fileItem.isFormField()){
					System.out.println(fileItem.getFieldName()+"-----------------------"+fileItem.getString("utf-8"));
				}else{
					if(fileItem.getSize()>0){
						//获取文件名而不是字段名字(处理兼容问题)
						String fieldName = fileItem.getName();
						
						//拿到文件名
						String name = FilenameUtils.getName(fieldName);
						if(!req.getServletContext().getMimeType(name).startsWith("image")){
							req.setAttribute("errorMsg", "文件类型不合适！");
							req.getRequestDispatcher("/jsp/login/register.jsp").forward(req, resp);
							return;
						}
						//获取随机的文件名
						name = UUID.randomUUID().toString().replaceAll("-", "")+"_"+name;
						
						//通过请求对象拿到输入流
						InputStream inputStream = fileItem.getInputStream();
						//通过请求对象获取servlet的上下文路径的真实路径
						
						String realPath = req.getServletContext().getRealPath("/upload");
						//（根据路径）创建一个文件对象
						File file = new File(realPath);
						if(!file.exists()){
							file.mkdirs();
						}
						//创建文件字节输出流
						FileOutputStream fileOutputStream = new FileOutputStream(new File(realPath,name));
						
						//将字节流包装成缓冲流
						BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
						IOUtils.copy(inputStream, bufferedOutputStream);
//						byte[] b = new byte[1024*10];
//						int len = -1;
//						while((len = inputStream.read(b)) != -1){
//							fileOutputStream.write(b, 0, len);
//						}
//						bufferedOutputStream.close();
						
						fileOutputStream.close();
						inputStream.close();
						
					}else{
						System.out.println("你没有上传文件");
					}	
				}
			}
		} catch (Exception e) {
			if(e instanceof SizeLimitExceededException){
				req.setAttribute("errorMsg", "太大！");
				req.getRequestDispatcher("/jsp/login/register.jsp").forward(req, resp);
			}else{
				e.printStackTrace();
			}
		}
	}
}
